package org.artifact.core.plugin.eventbus;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.artifact.core.lang.AbstractPlugin;
import org.artifact.core.server.ServerContext;

import java.util.Set;

public class GameEventPlugin extends AbstractPlugin {
	
	static final Log log = LogFactory.get(GameEventPlugin.class);
	
	private String listenerPkg;
	
	private String handlerPkg;
	
	private GameEventBus eventBus = new GameEventBus();
	
	@Override
	public boolean start() {
		// 注册监听器
		registerListener();
		// 注册处理器
		registerHandler();
		
		return true;
	}

	private void registerListener() {
		if (StrUtil.isEmpty(listenerPkg)){
			listenerPkg = ServerContext.me().rootPackage();
		}
		Set<Class<?>> scanClasss = ClassUtil.scanPackageBySuper(listenerPkg, GameEventListener.class);
		for (Class<?> scanClass : scanClasss) {
			GameEventListener listener = ReflectUtil.newInstance(GameEventListener.class, scanClass);
			eventBus.unregisterListener(listener);
		}
	}
	
	private void registerHandler() {
		if (StrUtil.isEmpty(handlerPkg)){
			handlerPkg = ServerContext.me().rootPackage();
		}
		Set<Class<?>> scanClasss = ClassUtil.scanPackageBySuper(handlerPkg, GameEventListener.class);
		for (Class<?> scanClass : scanClasss) {
			GameEventHandler handler = ReflectUtil.newInstance(GameEventHandler.class, scanClass);
			eventBus.unregisterHandler(handler);
		}
	}

	@Override
	public boolean stop() {
		return true;
	}

}
